package day06;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
class Student implements Serializable {

    @Serial
    private static final long serialVersionUID = 2492355079261757370L;
    private String name;
    private String description;
    private Integer age;
    private String address;
}

public class Serialize {
    public static void main(String[] args) {
        // 保存对象
        Student student = new Student("Hanserwei", "汉瑟薇", 18, "上海");
        saveObj(student);
        System.out.println("保存对象成功！");
        loadObj();
    }

    private static void loadObj() {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("student.txt"))) {
            Student student = (Student) objectInputStream.readObject();
            System.out.println(student);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void saveObj(Student student) {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("student.txt"))) {
            objectOutputStream.writeObject(student);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
